package weaver.aiyh_pcn.workflow_to_customer;


import aiyh.utils.zwl.common.ToolUtil;
import com.engine.crm.util.CrmCommonUtil;
import com.engine.crm.util.CrmRemindUtil;
import org.h2.util.StringUtils;
import weaver.aiyh_pcn.workflow_to_customer.config.CRM_Config;
import weaver.aiyh_pcn.workflow_to_customer.exception.DataExistsException;
import weaver.aiyh_pcn.workflow_to_customer.exception.LoginIdRepeatException;
import weaver.aiyh_pcn.workflow_to_customer.model.MainResult;
import weaver.aiyh_pcn.workflow_to_customer.utils.*;
import weaver.conn.RecordSet;
import weaver.crm.CrmShareBase;
import weaver.crm.Maint.*;
import weaver.crm.data.CustomerModifyLog;
import weaver.general.Util;
import weaver.hrm.city.CityComInfo;
import weaver.hrm.city.CitytwoComInfo;
import weaver.hrm.companyvirtual.DepartmentVirtualComInfo;
import weaver.hrm.companyvirtual.SubCompanyVirtualComInfo;
import weaver.hrm.outinterface.HrmOutInterface;
import weaver.hrm.province.ProvinceComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author EBU7-dev1-ayh
 * @create 2021-08-05 09:33
 * <p>
 * 功能：流程转客户， 这里逻辑十分复杂，估计我现在看的话也看不懂，如果这个需求要改，建议重写代码。
 * 不要问我为啥写这么复杂，因为我也刚来没多久就写这个东西，另外所有的字段都是可以通过配置
 * 实现没有太好的思路。只能使用笨办法，下一位有缘人修改的话，建议重写逻辑，阿巴阿巴阿巴巴
 * <p/>
 */
public class AddCustomer_Action extends ToolUtil implements Action {
    //当前类名称
    private final String className = "AddCustomer_Action";
    private RequestInfo request;
    MainResult mainResult;
    String tableName;
    String customerID;
    String subId;
    String deprtId;
    String resourceid;

    /**
     * 实现父类方法
     *
     * @param requestInfo
     * @return
     */
    @Override
    public String execute(RequestInfo requestInfo) {
        this.writeDebuggerLog(className, "------------" + className + " Begin -----------------");
        RecordSet rs = new RecordSet();
        this.request = requestInfo;
        //获取流程类型ID
        String workflowid = Util.null2String(requestInfo.getWorkflowid());
        //流程请求ID
        String requestid = Util.null2String(requestInfo.getRequestid());
        //流程表单名称
        this.tableName = requestInfo.getRequestManager().getBillTableName();
        this.writeDebuggerLog("这个是创建者id:" + requestInfo.getRequestManager().getCreater());
//      通过流程id查询表名
        if ("".equals(this.tableName)) {
            this.tableName = getBillTableNameByWorkflowId(workflowid);
        }
        this.writeDebuggerLog("wrokflowid:{" + workflowid + "},requestid:{" + requestid + "},tablename:{" + this.tableName + "}");
        CRM_Config config = new CRM_Config(workflowid, this.tableName, requestid);
        Map<String, List<Map<String, Object>>> configInfoMap = config.getConfigInfo();
        this.mainResult = config.getMainResult();
        try {
            if (this.mainResult.getChangeSetting() == 0) {
//			表示插入
                this.insertCustomerModel(this.mainResult, configInfoMap);
//				数据会写流程操作
                if (this.mainResult.getWillWrite() == 1) {
//					数据需要会写
                    ParaMap map = ParaMap.create().put(this.mainResult.getWillWriteField(), this.resourceid);
                    if ("main_table".equals(this.mainResult.getWillWriteTable())) {
//						数据会写到流程主表
                        this.updateHandle(this.tableName, map,
                                PrepSQLWhere.creatPrepWhere()
                                        .and("requestid").equal(requestid)
                                        .create());
                    } else {
//						数据回写到明细表中
                        this.updateHandle(this.mainResult.getWillWriteTable(), map,
                                PrepSQLWhere.creatPrepWhere()
                                        .and("mainid").equalSql("select id from " + this.tableName + " where requestid = " + requestid)
                                        .create());
                    }
                }
            } else {
//			 表示根据流程字段判断是插入还是更新
                String workflowName;
                if ("main_table".equals(this.mainResult.getUpdateInsertTable())) {
                    workflowName = this.tableName;
                    rs.executeQuery("select " + this.mainResult.getUpdateInsert() + " from " + workflowName + " where requestid = ?", requestid);
                } else {
                    workflowName = this.mainResult.getUpdateInsertTable();
                    rs.executeQuery("select " + this.mainResult.getUpdateInsert() + " from " + workflowName + " where mainid in (select id from " + this.tableName + " where requestid = ?)", requestid);
                }
                rs.next();
                int mark = Util.getIntValue(rs.getString(1), -1);
                if (mark != -1 && mark == this.mainResult.getInsertMark()) {
                    this.insertCustomerModel(this.mainResult, configInfoMap);
                } else if (mark != -1 && mark == this.mainResult.getUpdateMark()) {
                    this.updateCustomerModel(this.mainResult, configInfoMap, rs.getString(this.mainResult.getCustomerId()));
                }
            }
        } catch (LoginIdRepeatException e) {
            this.writeErrorLog(e + "\n");
            this.request.getRequestManager().setMessagecontent(aiyh.utils.Util.getHtmlLabelName(-91703,
                    request.getRequestManager().getUser().getLanguage(), "登录名重复，请重新输入登录名"));
            this.request.getRequestManager().setMessageid("1");
            return Action.FAILURE_AND_CONTINUE;
        } catch (Exception e) {
            this.writeDebuggerLog("insert customer error!");
            this.writeDebuggerLog(e + "\n");
            this.request.getRequestManager().setMessagecontent(aiyh.utils.Util.getHtmlLabelName(-91704,
                    request.getRequestManager().getUser().getLanguage(), "生成外部用户错误，请联系管理员！"));
            this.request.getRequestManager().setMessageid("2");
        } finally {
            this.writeDebuggerLog(className, "------------" + className + " End -----------------");
        }
        return Action.SUCCESS;

    }

    /**
     * 更新客户
     *
     * @param mainResult
     * @param configInfoMap
     * @param customerId
     */
    public void updateCustomerModel(MainResult mainResult, Map<String, List<Map<String, Object>>> configInfoMap, String customerId) {
        //		1、更新客户基本信息crm_customerinfo
        if (Utils.conformSql(configInfoMap, "CRM_CustomerInfo")) {
//			 将客户基本信息更新
            this.updateCustomerInfo(configInfoMap.get("CRM_CustomerInfo"), customerId);
        } else {
            return;
        }
//		2、判断更新客户联系信息crm_customercontacter
        if (Utils.conformSql(configInfoMap, "CRM_CustomerContacter") || this.mainResult.getIsOutUser() == 1 || this.mainResult.getIsOutUser() == 0) {
//			 将客户联系信息更新到客户联系表中
            if (Utils.conformSql(configInfoMap, "CRM_CustomerContacter")) {
                this.updateCustomerContacter(configInfoMap.get("CRM_CustomerContacter"), customerId);
            } else {
                this.updateCustomerContacter(configInfoMap.get("CRM_CustomerInfo"), customerId);
            }
        }
//		3、判断更新客户地址信息CRM_CustomerAddress
        if (Utils.conformSql(configInfoMap, "CRM_CustomerAddress")) {
//			 将客户信息更新到客户地址表中
            this.updateCustomerAddress(configInfoMap.get("CRM_CustomerAddress"), customerId);
        }
//		4、判断更新客户销售商机信息CRM_SellChance
        if (Utils.conformSql(configInfoMap, "CRM_SellChance")) {
//			 将客户联系信息更新到客户联系表中
            this.updateCustomerSellChance(configInfoMap.get("CRM_SellChance"), customerId);
        }
//		5、判断更新虚拟分部信息hrmsubcompanyvirtual
        if (Utils.conformSql(configInfoMap, "hrmsubcompanyvirtual") || this.mainResult.getIsOutUser() == 0) {
//			 将客户信息更新到虚拟分部信息表中
            this.updateHrmsubcompanyvirtual(configInfoMap.get("hrmsubcompanyvirtual"), customerId);
        } else {
            return;
        }
//		6、判断更新虚拟部门信息hrmdepartmentvirtual
        if (Utils.conformSql(configInfoMap, "hrmdepartmentvirtual") || this.mainResult.getIsOutUser() == 0) {
//			 见客户信息更新到虚拟部门信息表中
            this.updateHrmdepartmentvirtual(configInfoMap.get("hrmdepartmentvirtual"), customerId);
        } else {
            return;
        }
//		7、判断更新外部人员信息hrmresource
        if (Utils.conformSql(configInfoMap, "hrmResource") || this.mainResult.getIsOutUser() == 0) {
//			 将客户更新到外部人员信息表中
            this.updateHrmresource(configInfoMap.get("hrmResource"), customerId);
        }
    }

    /**
     * 更新客户基本信息
     *
     * @param mapList
     * @param customerId
     */
    public void updateCustomerInfo(List<Map<String, Object>> mapList, String customerId) {
        RecordSet rs = new RecordSet();
//		查询客户表，是否存在该客户，如果存在则对客户信息进行修改，如果不存在则跳过
        String querySql = "select * from crm_customerinfo where id = ?";
        rs.executeQuery(querySql, customerId);
        if (rs.next()) {
//			表示存在该客户，需要修改该客户的信息，并添加修改的 默认信息
            mapList.forEach(item -> this.updateCustomerInfo(item, customerId));
        }
    }

    /**
     * 更新客户基本信息
     *
     * @param map
     * @param customerId
     */
    public void updateCustomerInfo(Map<String, Object> map, String customerId) {
        map.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
        map.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
        this.updateHandle("crm_customerInfo", map,
                PrepSQLWhere.creatPrepWhere()
                        .and("id").equal(customerId)
                        .create());
    }

    /**
     * 更新客户联系人
     *
     * @param mapList
     * @param customerId
     */
    public void updateCustomerContacter(List<Map<String, Object>> mapList, String customerId) {
//		存在BUG,如果批量修改则会出现所有联系人都会被修改为同一个
        RecordSet rs = new RecordSet();
//		查询客户表，是否存在该客户，如果存在则对客户信息进行修改，如果不存在则跳过
        String querySql = "select * from crm_customercontacter where customerid = ?";
        rs.executeQuery(querySql, customerId);
        if (rs.next()) {
//			表示存在该客户，需要修改该客户的信息，并添加修改的 默认信息
            mapList.forEach(item -> {
                if (item.containsKey("fullname")) {
                    item.put("firstname", item.get("fullname"));
                }
                if (item.containsKey("firstname")) {
                    item.put("fullname", item.get("firstname"));
                }
                String query = "select id from CRM_CustomerContacter where customerid = ? and fullname = ?";
                rs.executeQuery(query, rs.getString("id"), item.get("fullname"));
                if (rs.next()) {
                    item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
                    item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
                    this.updateCustomerContacter(item, rs.getString("id"));
                }
            });
        }
    }

    /**
     * 更新客户联系人
     *
     * @param map
     * @param contacter
     */
    public void updateCustomerContacter(Map<String, Object> map, String contacter) {
        map.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
        map.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
        this.updateHandle("crm_customercontacter", map,
                PrepSQLWhere.creatPrepWhere()
                        .and("id").equal(contacter)
                        .create());
    }

    /**
     * 更新客户联系地址
     *
     * @param mapList
     * @param customerId
     */
    public void updateCustomerAddress(List<Map<String, Object>> mapList, String customerId) {
//		存在BUG,如果批量修改则会出现所有联系人都会被修改为同一个
        RecordSet rs = new RecordSet();
//		查询客户表，是否存在该客户，如果存在则对客户信息进行修改，如果不存在则跳过
        String querySql = "select * from crm_customeraddress where customerid = ?";
        rs.executeQuery(querySql, customerId);
        if (rs.next()) {
//			表示存在该客户，需要修改该客户的信息，并添加修改的 默认信息
            mapList.forEach(item -> {
                item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
                item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
                this.updateHandle("crm_customeraddress", item,
                        PrepSQLWhere.creatPrepWhere().and("customerid").equal(customerId)
                                .and("id").equal(rs.getString("id")).create());
            });
        }
    }

    /**
     * 更新客户商机
     *
     * @param mapList
     * @param customerId
     */
    public void updateCustomerSellChance(List<Map<String, Object>> mapList, String customerId) {
//		存在BUG,如果批量修改则会出现所有联系人都会被修改为同一个
        RecordSet rs = new RecordSet();
//		查询客户表，是否存在该客户，如果存在则对客户信息进行修改，如果不存在则跳过
        String querySql = "select * from crm_sellchance where customerid = ?";
        rs.executeQuery(querySql, customerId);
        if (rs.next()) {
//			表示存在该客户，需要修改该客户的信息，并添加修改的 默认信息
            mapList.forEach(item -> {
                item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
                item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
                this.updateHandle("crm_sellchance", item,
                        PrepSQLWhere.creatPrepWhere().and("customerid").equal(customerId)
                                .and("id").equal(rs.getString("id")).create());
            });
        }
    }

    /**
     * 更新人员虚拟分部信息
     *
     * @param mapList
     * @param customerId
     */
    public void updateHrmsubcompanyvirtual(List<Map<String, Object>> mapList, String customerId) {
        //		存在BUG,如果批量修改则会出现所有联系人都会被修改为同一个
        RecordSet rs = new RecordSet();
        String querySql = "select * from crm_customerinfo where id = ?";
        rs.executeQuery(querySql, customerId);
        CustomerInfoComInfo customerInfoComInfo = new CustomerInfoComInfo();
//		查询客户表，是否存在该客户，如果存在则对客户信息进行修改，如果不存在则跳过
        querySql = "select * from hrmsubcompanyvirtual where id = ?";
        if (rs.next()) {
            rs.executeQuery(querySql, this.subId);
            if (rs.next()) {
//			表示存在该客户，需要修改该客户的信息，并添加修改的 默认信息
                mapList.forEach(item -> {
                    this.updateHandle("hrmsubcompanyvirtual", item,
                            PrepSQLWhere.creatPrepWhere()
                                    .and("id").equal(rs.getString("id")).create());
                });
            }
        }
    }

    /**
     * 更新人员虚拟部门信息
     *
     * @param mapList
     * @param customerId
     */
    public void updateHrmdepartmentvirtual(List<Map<String, Object>> mapList, String customerId) {
//		存在BUG,如果批量修改则会出现所有联系人都会被修改为同一个
        RecordSet rs = new RecordSet();
        String querySql = "select * from crm_customerinfo where id = ?";
        rs.executeQuery(querySql, customerId);
        CustomerInfoComInfo customerInfoComInfo = new CustomerInfoComInfo();
//		查询客户表，是否存在该客户，如果存在则对客户信息进行修改，如果不存在则跳过
        querySql = "select * from hrmdepartmentvirtual where id = ?";
        if (rs.next()) {
            rs.executeQuery(querySql, this.deprtId);
            if (rs.next()) {
//			表示存在该客户，需要修改该客户的信息，并添加修改的 默认信息
                mapList.forEach(item -> {
                    this.updateHandle("hrmdepartmentvirtual", item,
                            PrepSQLWhere.creatPrepWhere()
                                    .and("id").equal(rs.getString("id")).create());
                });
            }
        }
    }

    public void updateHrmresource(List<Map<String, Object>> mapList, String customerId) {
//		先查询外部用户与人员表的对应关系

    }

    public void insertCustomerModel(MainResult mainResult, Map<String, List<Map<String, Object>>> configInfoMap) {
        Map<String, Object> customer;
//		1、插入客户基本信息crm_customerinfo
        if (Utils.conformSql(configInfoMap, "CRM_CustomerInfo")) {
//			 将客户基本信息插入表中
            customer = this.insertCustomerInfo(configInfoMap.get("CRM_CustomerInfo"));
        } else {
            return;
        }
//		2、判断插入客户联系信息crm_customercontacter
        if (Utils.conformSql(configInfoMap, "CRM_CustomerContacter") || this.mainResult.getIsOutUser() == 1 || this.mainResult.getIsOutUser() == 0) {
//			 将客户联系信息插入到客户联系表中
            if (Utils.conformSql(configInfoMap, "CRM_CustomerContacter")) {
                this.insertCustomerContacter(configInfoMap.get("CRM_CustomerContacter"), customer, 0);
            } else {
                this.insertCustomerContacter(configInfoMap.get("CRM_CustomerInfo"), customer, 1);
            }
        }
//		3、判断插入客户地址信息CRM_CustomerAddress
        if (Utils.conformSql(configInfoMap, "CRM_CustomerAddress")) {
//			 将客户信息出入到客户地址表中
            this.insertCustomerAddress(configInfoMap.get("CRM_CustomerAddress"), customer);
        }
//		4、判断插入客户销售商机信息CRM_SellChance
        if (Utils.conformSql(configInfoMap, "CRM_SellChance")) {
//			 将客户联系信息插入到客户联系表中
            this.insertCustomerSellChance(configInfoMap.get("CRM_SellChance"), customer);
        }
/*//		5、判断插入虚拟分部信息hrmsubcompanyvirtual

		if (Utils.conformSql(configInfoMap, "hrmsubcompanyvirtual") || this.mainResult.getIsOutUser() == 0) {
//			 将客户信息插入到虚拟分部信息表中
			this.subId = this.insertHrmsubcompanyvirtual(configInfoMap.get("hrmsubcompanyvirtual"), customer);
		} else {
			return;
		}
//		6、判断插入虚拟部门信息hrmdepartmentvirtual

		if (Utils.conformSql(configInfoMap, "hrmdepartmentvirtual") || this.mainResult.getIsOutUser() == 0) {
//			 见客户信息插入到虚拟部门信息表中
			this.deprtId = this.insertHrmdepartmentvirtual(configInfoMap.get("hrmdepartmentvirtual"), customer, subId);
		} else {
			return;
		}*/
//		7、判断插入外部人员信息hrmresource
        if (Utils.conformSql(configInfoMap, "hrmResource") || this.mainResult.getIsOutUser() == 0) {
//			 将客户插入到外部人员信息表中
            this.insertHrmresource(configInfoMap.get("hrmResource"), customer, subId, deprtId);
        }
    }

    public void insertHrmresourceVirtual(Map<String, Object> customer, String hrmid, String subId, String deparId) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select max(id) from HrmResourceVirtual");
        int hrmvId = 0;
        if (rs.next()) {
            hrmvId = rs.getInt(1) + 1;
        }
        int finalHrmvId = hrmvId;
        int finalHrmvId1 = hrmvId;
        String queryCompanyId = "select id from HrmCompanyVirtual where companyname like '%客户维度%'";
        rs.executeQuery(queryCompanyId);
        rs.next();
        String companyId = rs.getString("id");
        Map<String, Object> hrmrVmap = Utils.createMap()
                .uPut("id", finalHrmvId)
                .uPut("resourceid", finalHrmvId1)
                .uPut("managerid", 0)
                .uPut("subcompanyid", subId)
                .uPut("departmentid", deparId)
                .uPut("managerstr", "")
                .uPut("virtualtype", companyId);
        this.insertHandle("HrmResourceVirtual", hrmrVmap);
        Map<String, Object> hrmOMap = Utils.createMap()
                .uPut("resourceid", hrmid)
                .uPut("wxname", Util.null2String(customer.get("wxname")))
                .uPut("wxopenid", Util.null2String(customer.get("wxopenid")))
                .uPut("wxuuid", Util.null2String(customer.get("wxuuid")))
                .uPut("customid", customer.get("customerId"))
                .uPut("country", Util.null2String(customer.get("country")))
                .uPut("province", Util.null2String(customer.get("province")))
                .uPut("city", Util.null2String(customer.get("city")))
                .uPut("customfrom", Util.null2String(customer.get("customfrom")))
                .uPut("isoutmanager", 0);
        this.insertHandle("hrmresourceout", hrmOMap);
    }

    public void insertHrmresource(List<Map<String, Object>> mapList, Map<String, Object> customer, String subId, String deparId) {

        CrmCommonUtil crmCommonUtil = new CrmCommonUtil();
        mapList.forEach(item -> {
            RecordSet rs = new RecordSet();
//            String hrmid;
////			获取人员id
//            rs.executeProc("HrmResourceMaxId_Get", "");
//            rs.next();
//            hrmid = rs.getString(1);
//			整理数据
            item.put("createdate", Utils.getTime("yyyy-MM-dd"));
//			item.put("id", hrmid);
            item.put("createrid", this.request.getRequestManager().getCreater());
            if (!item.containsKey("lastname")) {
                item.put("lastname", customer.get("name"));
            }
            if (!item.containsKey("loginid")) {
                item.put("loginid", crmCommonUtil.getPinYin((String) customer.get("name"), 7).get("pinyin"));
            }
            if (item.containsKey("seclevel") && Integer.parseInt((String) item.get("seclevel")) > 0) {
                item.put("seclevel", -10);
            }
            if (!item.containsKey("seclevel")) {
                item.put("seclevel", -10);
            }
            if (!item.containsKey("password")) {
                item.put("password", Util.getEncrypt((String) crmCommonUtil.getPinYin((String) customer.get("name"), 7).get("pinyin")));
            }
            if (item.containsKey("password")) {
                item.put("password", Util.getEncrypt((String) item.get("password")));
            }
            if (!item.containsKey("lastmoddate")) {
                item.put("lastmoddate", Utils.getTime("yyyy-MM-dd"));
            }
            if (!item.containsKey("lastmodid")) {
                item.put("lastmodid", 1);
            }
            if (!item.containsKey("systemlanguage")) {
                item.put("systemlanguage", 7);
            }
            if (!item.containsKey("departmentid")) {
//				customerInfo.getCustomerInfoSubcompanyid(String.valueOf(customer.get("customerId")))
                item.put("departmentid", deprtId);
            }
            if (!item.containsKey("subcompanyid1")) {
//				customerInfo.getCustomerInfoDepartmentid(String.valueOf(customer.get("customerId")))
                item.put("subcompanyid1", subId);
            }
            if (!item.containsKey("status")) {
                item.put("status", 1);
            }
            if (!item.containsKey("accounttype")) {
                item.put("accounttype", 0);
            }
            if (!item.containsKey("dsporder")) {
//				item.put("dsporder", hrmid);
            }
            item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) customer.get("name"), 7));
//			查询loginid是否已经存在
            String quertLogin = "select count(1) from hrmresource where loginid= ?";
            rs.executeQuery(quertLogin, item.get("loginid"));
            if (rs.next() && rs.getInt(1) > 0) {
//				存在登录名
                throw new LoginIdRepeatException("loginid is repeat,Please re-enter logind!");
            }
            //			this.insertHandle("hrmresource", item);
//			if (this.mainResult.getManagerType() == 3) {
//				//			将外部客户的客户经理更新为当前插入的外部用户，方便外部用户参与流程审批
//				this.updateHandle("CRM_CustomerInfo", Utils.createMap().uPut("manager", Integer.parseInt(hrmid) + 1)
//								.uPut("lastupdatedtime", Utils.getTime("HH:mm:ss"))
//								.uPut("lastupdatedtime", Utils.getTime("HH:mm:ss")),
//						PrepSQLWhere.creatPrepWhere()
//								.and("id").equal(customer.get("customerId"))
//								.create());
//			}
            HrmOutInterface hrmOutInterface = new HrmOutInterface();
            Map<String, String> param = new HashMap<>();
            param.put("crmid", Util.null2String(customer.get("customerId")));
            param.put("lastname", Util.null2String(item.get("lastname")));
            param.put("loginid", Util.null2String(item.get("loginid")));
            param.put("password", Util.null2String(item.get("password")));
            param.put("seclevel", Util.null2String(item.get("seclevel")));
            param.put("mobile", Util.null2String(item.get("mobile")));
            param.put("email", Util.null2String(item.get("email")));
            param.put("isoutmanager", Util.null2s(Util.null2String(item.get("isoutmanager")), "1"));
            param.put("wxname", Util.null2String(item.get("wxname")));
            param.put("wxopenid", Util.null2String(item.get("wxopenid")));
            param.put("wxuuid", Util.null2String(item.get("wxuuid")));
            param.put("country", Util.null2String(item.get("country")));
            param.put("province", Util.null2String(item.get("province")));
            param.put("city", Util.null2String(item.get("city")));
            param.put("customfrom", Util.null2String(item.get("customfrom")));
            Map<String, String> returnObj = hrmOutInterface.createResource4Card(param);
            String resourceid = returnObj.get("resourceid");
            String errorinfo = returnObj.get("errorinfo");
            if (!"".equals(errorinfo)) {
                throw new RuntimeException(errorinfo);
            }
            String sql = "INSERT INTO CRM_ShareInfo (relateditemid, sharetype, seclevel, sharelevel, crmid, contents, deleted, seclevelMax, jobtitleid, joblevel, scopeid) VALUES (?, '1', '10','1','0',?, '0', '100', ?, '0', ',0,')";
            rs.executeUpdate(sql, customer.get("customerId"), resourceid, resourceid);
            this.resourceid = resourceid;


            CustomerInfoComInfo customerInfo = new CustomerInfoComInfo();
            customerInfo.removeCustomerInfoCache();
            customerInfo.removeCache();
            (new CustomerDescComInfo()).removeCache();
            (new CustomerRatingComInfo()).removeCache();
            (new CustomerSizeComInfo()).removeCache();
            (new CustomerStatusComInfo()).removeCache();
            customerInfo.addCustomerInfoCache(String.valueOf(customer.get("customerId")));
            CrmRemindUtil crmRemindUtil = new CrmRemindUtil(request.getRequestManager().getUser());
            crmRemindUtil.outResourceAddRemind(Integer.parseInt(resourceid));

//			应该是
//			hrmOutInterface.initMatrixDataOutManager(subId, hrmid);

            ResourceComInfo resourceComInfo = null;
            try {
                resourceComInfo = new ResourceComInfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!Objects.isNull(resourceComInfo)) {
                resourceComInfo.removeResourceCache();
                resourceComInfo.removeCache();
            }
//			this.insertHrmresourceVirtual(customer, hrmid, subId, deparId);
//			Map<String, Object> map = new HashMap<String, Object>() {{
//				put("relateditemid", Util.null2String(customer.get("customerId")));
//				put("sharetype", "1");
//				put("seclevel", "10");
//				put("sharelevel", "1");
//				put("crmid", "0");
//				put("contents", hrmid);
//				put("deleted", "0");
//				put("seclevelMax", "100");
//				put("jobtitleid", hrmid);
//				put("joblevel", "0");
//				put("scopeid", "0");
//			}};
//			this.insertHandle("CRM_ShareInfo", map);
        });
    }

    public String insertHrmdepartmentvirtual(List<Map<String, Object>> mapList, Map<String, Object> customer, String subId) {
        if (Objects.isNull(mapList) || mapList.isEmpty()) {
            mapList = new ArrayList<>();
            mapList.add(new HashMap<>());
        }
        CrmCommonUtil crmCommonUtil = new CrmCommonUtil();
        RecordSet rs = new RecordSet();
        String queryCompanyId = "select id from HrmCompanyVirtual where companyname like '%客户维度%'";
        rs.executeQuery(queryCompanyId);
        rs.next();
        String companyId = rs.getString("id");
//		查询是否存在客户经理的部门
        String querydepartment = "select id from hrmdepartmentvirtual where subcompanyid1 = ? and departmentname = ?";
        rs.executeQuery(querydepartment, subId, "客户经理");
        if (rs.next()) {
            this.insertHandle("hrmdepartmentvirtual", new ArrayList<Map<String, Object>>() {{
                add(new HashMap<String, Object>() {
                    {
                        put("departmentname", "客户经理");
                        put("departmentmark", "客户经理");
                        put("subcompanyid1", subId);
                        put("showOrderOfTree", "0");
                        put("virtualtype", companyId);
                        put("ecology_pinyin_search", crmCommonUtil.getPinYin("客户经理", 7));
                    }
                });
            }});
        }
        String queryderId = "select id from hrmdepartmentvirtual where subcompanyid1 = ? and departmentname = ?";
        rs.executeQuery(queryderId, subId, customer.get("name"));
        if (!rs.next()) {
            mapList.forEach(item -> {
                item.put("departmentname", customer.get("name"));
                item.put("departmentmark", customer.get("name"));
                item.put("subcompanyid1", subId);
                item.put("showOrderOfTree", "0");
                item.put("virtualtype", companyId);
                item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) customer.get("name"), 7));
            });
            this.insertHandle("hrmdepartmentvirtual", mapList);
            DepartmentVirtualComInfo departmentVirtualComInfo = new DepartmentVirtualComInfo();
            departmentVirtualComInfo.removeCache();
            departmentVirtualComInfo.removeDepartmentCache();
            rs.executeQuery(queryderId, subId, customer.get("name"));
            rs.next();
            return rs.getString(1);
        }
        return rs.getString(1);
    }

    public String insertHrmsubcompanyvirtual(List<Map<String, Object>> mapList, Map<String, Object> customer) {
        if (Objects.isNull(mapList) || mapList.isEmpty()) {
            mapList = new ArrayList<>();
            mapList.add(new HashMap<>());
        }
        CrmCommonUtil crmCommonUtil = new CrmCommonUtil();
        RecordSet rs = new RecordSet();
        String queryCompanyId = "select id from HrmCompanyVirtual where companyname like '%客户维度%'";
        rs.executeQuery(queryCompanyId);
        rs.next();
        String companyId = rs.getString("id");
        String quertSupsubcomId = "select id from hrmsubcompanyvirtual where subcompanyname = '新用户'";
        rs.executeQuery(quertSupsubcomId);
        rs.next();
        String supcomId = rs.getString("id");
        String querySubID = "select id from hrmsubcompanyvirtual where subcompanyname = ?";
        rs.executeQuery(querySubID, customer.get("name"));
        if (!rs.next()) {
            mapList.forEach(item -> {
                item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) customer.get("name"), 7));
                item.put("subcompanyname", customer.get("name"));
                item.put("subcompanydesc", customer.get("name"));
                item.put("companyid", companyId);
                item.put("virtualtypeid", companyId);
                item.put("supsubcomid", supcomId);
            });
            this.insertHandle("hrmsubcompanyvirtual", mapList);
            SubCompanyVirtualComInfo subCompanyVirtualComInfo = new SubCompanyVirtualComInfo();
            subCompanyVirtualComInfo.removeCache();
            subCompanyVirtualComInfo.removeSubCompanyCache();
            rs.executeQuery(querySubID, customer.get("name"));
            rs.next();
            return rs.getString("id");
        }
        return rs.getString("id");
    }

    public void insertCustomerSellChance(List<Map<String, Object>> mapList, Map<String, Object> customer) {
        mapList.forEach(item -> {
            item.put("customerid", Util.null2String(customer.get("customerId")));
            item.put("createdate", Utils.getTime("yyyy-MM-dd"));
            item.put("createtime", Utils.getTime("HH:mm:ss"));
            item.put("createrid", this.request.getRequestManager().getCreater());
            item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
            item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
            item.put("creater", this.request.getRequestManager().getCreater());
        });
        this.insertHandle("CRM_SellChance", mapList);
    }

    public void insertCustomerAddress(List<Map<String, Object>> mapList, Map<String, Object> customer) {
        RecordSet rs = new RecordSet();
        mapList.forEach(item -> {
            item.put("customerid", Util.null2String(customer.get("customerId")));
            item.put("createdate", Utils.getTime("yyyy-MM-dd"));
            item.put("createtime", Utils.getTime("HH:mm:ss"));
            item.put("createrid", this.request.getRequestManager().getCreater());
            item.put("lastupdatedby", this.request.getRequestManager().getCreater());
            item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
            item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
            if (item.containsKey("contacter")) {
                if (Util.getIntValue(String.valueOf(item.get("contacter")), 0) == 0) {
                    String queryContacter = "select id from crm_customercontacter where customerid = ? and (fullname = ? or firstname = ?)";
                    rs.executeUpdate(queryContacter, customer.get("customerId"), item.get("contacter"), item.get("contacter"));
                    rs.next();
                    item.put("contacter", rs.getString(1));
                }
            }
        });
        this.insertHandle("crm_customeraddress", mapList);
    }

    public void insertCustomerContacter(List<Map<String, Object>> mapList, Map<String, Object> customer, int type) {
        CrmCommonUtil crmCommonUtil = new CrmCommonUtil();
        RecordSet rs = new RecordSet();
        String querySql = "select id from CRM_CustomerContacter where customerid = ? and fullname = ?";

        if (type == 1) {
            if (rs.executeQuery(querySql, Util.null2String(customer.get("customerId")), Util.null2String(customer.get("name"))) && rs.next()) {
//			已存在相关的联系人
                return;
            }
//			表示需要创建联系人，但是没有指定联系人对应的流程字段，则默认将客户信息当做联系人信息，并且设置为主联系人
            Map<String, Object> map = new HashMap<>();
            map.put("customerid", Util.null2String(customer.get("customerId")));
            map.put("fullname", Util.null2String(customer.get("name")));
            map.put("firstname", Util.null2String(customer.get("name")));
            map.put("jobtitle", Util.null2String(customer.get("name")));
            map.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) customer.get("name"), 7));
            map.put("main", 1);
            map.put("email", Util.null2String(customer.get("email")));
            map.put("mobilephone", Util.null2String(customer.get("phone")));
            map.put("manager", Util.null2String(customer.get("manager")));
            map.put("department", Util.null2String(customer.get("department")));
            map.put("createdate", Utils.getTime("yyyy-MM-dd"));
            map.put("createtime", Utils.getTime("HH:mm:ss"));
            map.put("createrid", this.request.getRequestManager().getCreater());
            map.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
            map.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
            this.insertHandle("crm_customercontacter", new ArrayList<Map<String, Object>>() {{
                add(map);
            }});
            return;
        }
        AtomicBoolean flag = new AtomicBoolean(true);
        mapList.forEach(item -> {
            if (flag.get()) {
                item.put("main", 1);
                flag.set(false);
            }
            if (!item.containsKey("fullname") && !item.containsKey("firstname")) {
                item.put("fullname", Util.null2String(customer.get("name")));
                item.put("firstname", Util.null2String(customer.get("name")));
                item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) customer.get("name"), 7));
            }
            if (item.containsKey("fullname")) {
                item.put("fullname", Util.null2String(item.get("fullname")));
                item.put("firstname", Util.null2String(item.get("fullname")));
                item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) item.get("fullname"), 7));
            }
            if (item.containsKey("firstname")) {
                item.put("fullname", Util.null2String(item.get("firstname")));
                item.put("firstname", Util.null2String(item.get("firstname")));
                item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) item.get("firstname"), 7));
            }
            if (!item.containsKey("jobtitle")) {
                item.put("jobtitle", Util.null2String(customer.get("name")));
            }
            if (!item.containsKey("mobilephone")) {
                item.put("mobilephone", Util.null2String(customer.get("phone")));
            }
            if (!item.containsKey("email")) {
                item.put("email", Util.null2String(customer.get("email")));
            }
            if (rs.executeQuery(querySql, Util.null2String(customer.get("customerId")), Util.null2String(customer.get("name"))) && rs.next()) {
//			已存在相关的联系人
                this.updateCustomerContacter(item, rs.getString("id"));
            }
            item.put("customerid", Util.null2String(customer.get("customerId")));
            item.put("createdate", Utils.getTime("yyyy-MM-dd"));
            item.put("createtime", Utils.getTime("HH:mm:ss"));
            item.put("createrid", this.request.getRequestManager().getCreater());
            item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
            item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
        });
        this.insertHandle("crm_customercontacter", mapList);
        CustomerContacterComInfo customerComInfo = new CustomerContacterComInfo();
        customerComInfo.removeCustomerContacterCache();
        customerComInfo.removeCache();
    }

    public Map<String, Object> insertCustomerInfo(List<Map<String, Object>> mapList) {
        RecordSet rs = new RecordSet();
        String managerId;
        if (this.mainResult.getManagerType() == 0) {
//          客户经理根据流程字段绑定
            rs.executeQuery("select " + this.mainResult.getManagerField() + " from " + this.tableName + " where requestid = ?",
                    this.request.getRequestid());
            rs.next();
            managerId = Util.null2String(rs.getString(1));
            if (StringUtils.isNullOrEmpty(managerId) || "".equals(managerId)) {
                managerId = String.valueOf(this.request.getRequestManager().getCreater());
            }
        } else if (this.mainResult.getManagerType() == 1) {
//          客户经理为固定值
            managerId = String.valueOf(this.mainResult.getCustomerManager());
        } else {
//			客户经理为流程创建者或外部用户
            managerId = String.valueOf(this.request.getRequestManager().getCreater());
        }
        String creditlevel = "0";
//		表示含有信用保证金额，需要调用存储过程
        final Map<String, Object> cusMap = mapList.get(0);
        if (!cusMap.containsKey("creditamount")) {
            if (cusMap.get("creditamount") != null && !"".equals(cusMap.get("creditamount").toString().trim())) {
                rs.executeProc("Sales_CRM_CreditInfo_Select", cusMap.get("creditamount") + "");
                if (rs.next()) {
                    creditlevel = rs.getString(1);
                }
            }
        }
//		 添加必要参数
        CityComInfo cityComInfo = new CityComInfo();
        ResourceComInfo resourceComInfo = null;
        try {
            resourceComInfo = new ResourceComInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResourceComInfo finalResourceComInfo = resourceComInfo;
        ProvinceComInfo province = new ProvinceComInfo();
        String finalCreditlevel = creditlevel;
        String finalManagerId = managerId;
        CrmCommonUtil crmCommonUtil = new CrmCommonUtil();
        AtomicReference<String> customerIdStr = new AtomicReference<>();
        try {
            mapList.forEach(item -> {

//			判断字段，特殊字段特殊处理
                if (item.containsKey("province")) {
                    if (!"".equals(item.get("province")) && Util.getIntValue((String) item.get("province"), 0) > 0) {
                        item.put("country", province.getProvincecountryid((String) item.get("province")));
                    }
                }
                if (item.containsKey("city")) {
                    if (!"".equals(item.get("city")) && Util.getIntValue(item.get("city").toString(), 0) > 0) {
//					如果城市字段属于int类型的，则将城市字段进行替换，并且添加国家字段
                        item.put("city", cityComInfo.getCityprovinceid((String) item.get("city")));
                        item.put("country", cityComInfo.getCitycountryid((String) item.get("city")));
                    }
                }
                if (item.containsKey("district")) {
                    if (!"".equals(item.get("district")) && Util.getIntValue((String) item.get("district"), 0) > 0) {
                        CitytwoComInfo citytwoComInfo = new CitytwoComInfo();
                        item.put("city", citytwoComInfo.getCitypid((String) item.get("district")));
                        item.put("province", cityComInfo.getCityprovinceid((String) item.get("city")));
                        item.put("country", province.getProvincecountryid((String) item.get("province")));
                    }
                }
                if (item.containsKey("type")) {
                    item.put("type", 1);
                }
                if (item.containsKey("mobilephone")) {
                    item.put("phone", item.get("mobilephone"));
                    item.remove("mobilephone");
                }
                if (item.containsKey("contacteremail")) {
                    item.put("email", item.get("contacteremail"));
                    item.remove("contacteremail");
                }

                if (item.containsKey("engname")) {
                    item.put("name", item.get("engname"));
                }
                if (item.containsKey("name")) {
                    item.put("engname", item.get("name"));
                }

                if (item.containsKey("location")) {
                    if (!"".equals(item.get("location"))) {
                        String lng = item.get("location").toString().split(",")[0];
                        String lat = item.get("location").toString().split(",")[1];
                        item.put("lng1", lng);
                        item.put("lat1", lat);
                    }
                }
                if (!item.containsKey("lastupdatedby")) {
                    item.put("lastupdatedby", this.request.getRequestManager().getCreater());
                }
                if (!item.containsKey("status")) {
                    item.put("status", 2);
                }
                if (!item.containsKey("language")) {
                    item.put("language", 7);
                }
                if (!item.containsKey("fincode")) {
                    item.put("fincode", 0);
                }
                if (!item.containsKey("currency")) {
                    item.put("currency", 0);
                }
                if (!item.containsKey("contractlevel")) {
                    item.put("contractlevel", 0);
                }
                if (!item.containsKey("creditoffset")) {
                    item.put("creditoffset", 0);
                }
                if (!item.containsKey("discount")) {
                    item.put("discount", 100);
                }
                if (!item.containsKey("invoiceacount")) {
                    item.put("invoiceacount", 0);
                }
                if (!item.containsKey("deliverytype")) {
                    item.put("deliverytype", 0);
                }
                if (!item.containsKey("paymentterm")) {
                    item.put("paymentterm", 0);
                }
                if (!item.containsKey("paymentway")) {
                    item.put("paymentway", 0);
                }
                if (!item.containsKey("saleconfirm")) {
                    item.put("saleconfirm", 0);
                }
                if (!item.containsKey("PortalStatus")) {
                    item.put("PortalStatus", 0);
                }
                if (!item.containsKey("deleted")) {
                    item.put("deleted", 0);
                }
                if (item.containsKey("seclevel")) {
                    item.put("seclevel", (Integer) item.get("seclevel") >= 0 ? -1 : item.get("seclevel"));
                }
                if (item.containsKey("name")) {
                    //		判断客户是否存在，通过用户id和客户姓名
                    String querySql = "select * from crm_customerInfo where deleted <> 1 and name = ? and manager =?";
                    if (rs.executeQuery(querySql, item.get("name"), finalManagerId) && rs.next()) {
                        //       如果客户名重复则特殊处理，如果如果该客户就进行更新
                        customerIdStr.set(rs.getString("id"));
                        this.updateCustomerInfo(item, customerIdStr.get());
                        throw new DataExistsException("break now forEach");
//					String newName = item.get("name") + String.valueOf(System.currentTimeMillis());
//					item.put("name", newName);
//					item.put("engname", newName);
                    }
                }
                item.put("createdate", Utils.getTime("yyyy-MM-dd"));
                item.put("createtime", Utils.getTime("HH:mm:ss"));
                item.put("createrid", this.request.getRequestManager().getCreater());
                item.put("lastupdateddate", Utils.getTime("yyyy-MM-dd"));
                item.put("lastupdatedtime", Utils.getTime("HH:mm:ss"));
                item.put("department", finalResourceComInfo.getDepartmentID(finalManagerId));
                item.put("subcompanyid1", finalResourceComInfo.getSubCompanyID(finalManagerId));
                item.put("manager", finalManagerId);
                item.put("creditlevel", finalCreditlevel);
                item.put("typebegin", Utils.getTime("yyyy-MM-dd"));
                item.put("ecology_pinyin_search", crmCommonUtil.getPinYin((String) item.get("name"), 7));

            });
        } catch (DataExistsException e) {
            cusMap.put("customerId", customerIdStr.get());
            this.customerID = customerIdStr.get();
            return cusMap;
        }
//		 插入客户基本信息
        this.insertHandle("CRM_CustomerInfo", mapList);
        CustomerInfoComInfo customerInfo = new CustomerInfoComInfo();

        customerInfo.removeCustomerInfoCache();
        customerInfo.removeCache();
        String queryIdSql = "select max(id) from CRM_CustomerInfo where name= ? and manager = ?";
        String customerId = "";
        rs.executeQuery(queryIdSql, cusMap.get("name"), managerId);
        if (rs.next()) {
            customerId = rs.getString(1);
            customerInfo.addCustomerInfoCache(customerId);
            if (!"".equals(customerId)) {
                CustomerModifyLog customerModifyLog = new CustomerModifyLog();
                customerModifyLog.modify(customerId, String.valueOf(this.request.getRequestManager().getCreater()), managerId);
                CrmShareBase crmShareBase = new CrmShareBase();
                try {
                    crmShareBase.setDefaultShare("" + customerId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            this.writeDebuggerLog("this not this customer in database, customer name is: " + cusMap.get("name"));
        }

        customerInfo.removeCustomerInfoCache();
        customerInfo.removeCache();
        (new CustomerDescComInfo()).removeCache();
        (new CustomerRatingComInfo()).removeCache();
        (new CustomerSizeComInfo()).removeCache();
        (new CustomerStatusComInfo()).removeCache();
        customerInfo.addCustomerInfoCache(customerId);
        if (cusMap.containsKey("agent") && !StringUtils.isNullOrEmpty(String.valueOf(cusMap.containsKey("agent")))) {
            String finalCustomerId = customerId;
            Map<String, Object> map = new HashMap<String, Object>() {{
                put("relateditemid", finalCustomerId);
                put("sharetype", "9");
                put("sharelevel", "1");
                put("crmid", "0");
                put("contents", cusMap.containsKey("agent"));
                put("deleted", "0");
            }};
            this.insertHandle("CRM_ShareInfo", map);
        }
        cusMap.put("customerId", customerId);
        this.customerID = customerId;
//		@debug
        return cusMap;
    }

    public void insertHandle(String tableName, List<Map<String, Object>> mapList) {
        RecordSet rs = new RecordSet();
        if (mapList.size() == 1) {
//			 单条数据插入
            this.insertHandle(tableName, mapList.get(0));
        } else {
            mapList.forEach(item -> this.insertHandle(tableName, item));
        }

    }

    public void insertHandle(String tableName, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
//			 单条数据插入
        SqlResult sqlResult = BuilderSqlUtil.builderInsertSql(tableName, map);
        if (!Objects.isNull(sqlResult)) {
//			 插入数据库数据
            this.writeDebuggerLog(sqlResult.getSqlStr());
            this.writeDebuggerLog(Arrays.toString(sqlResult.getArgs()) + "\n");
            rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
        }
    }

    public void updateHandle(String tableName, List<Map<String, Object>> mapList, PrepSQLWhere where) {
        RecordSet rs = new RecordSet();

        if (mapList.size() == 1) {
//			 单条数据插入
            this.updateHandle(tableName, mapList.get(0), where);
        } else {
            mapList.forEach(item -> this.updateHandle(tableName, item, where));
        }

    }

    public void updateHandle(String tableName, Map<String, Object> map, PrepSQLWhere where) {
        RecordSet rs = new RecordSet();
//			 单条数据插入
        SqlResult sqlResult = BuilderSqlUtil.builderUpdateSql(tableName, map, where);
        //			 插入数据库数据
//		Console.log(sqlResult.getSqlStr());
//		Console.log(Arrays.toString(sqlResult.getArgs()) + "\n");
        this.writeDebuggerLog(sqlResult.getSqlStr());
        this.writeDebuggerLog(Arrays.toString(sqlResult.getArgs()) + "\n");
        rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
    }


}
